from PIL import Image
import numpy as np
import os
from lineless_table_rec import LinelessTableRecognition
from lineless_table_rec.utils_table_recover import format_html, plot_rec_box_with_logic_info, plot_rec_box
from table_cls import TableCls
from wired_table_rec import WiredTableRecognition
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
card_detection_correction = pipeline(Tasks.card_detection_correction, model='damo/cv_resnet18_card_correction')
WiredTableRecognition_engine = WiredTableRecognition()

from rapidocr_onnxruntime import RapidOCR
#from rapidocr_paddle import RapidOCR
ocr_engine = RapidOCR()

def ocr_one(img_path,filename):
    img_path_file=os.path.join(img_path, filename)
    resultc = card_detection_correction(img_path_file)
    result, elapse = ocr_engine(resultc['output_imgs'][0], use_det=True, use_cls=True, use_rec=True)
    image = Image.fromarray(resultc['output_imgs'][0])
    img_path_file_new = os.path.join('tmp/images', filename)
    image.save(img_path_file_new)
    html, elasp, polygons, logic_points, ocr_res,yy = WiredTableRecognition_engine(img_path_file_new,result)
    Text = ""
    for res in result:
        box = [res[0][0][0],res[0][0][1],res[0][2][0],res[0][2][1]]
        text = res[1]
        boxs = [box,text]
        if boxs not in yy:
            Text = Text + text+" "
    for res in html:
        table = ""
        for r in res['t_ocr_res']:
            table=table+r[1]+"  "
        #print(table)
        Text=Text+table+"  "
    return Text